<script setup>
import { ref, nextTick } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { noticeMgrAddService, noticeMgrUpdateService } from "@/api";
import { useUserStore } from "@/stores";

// 使用用户存储模块
const userInfo = useUserStore();
// 抽屉的可见性状态
const visibleDrawer = ref(false);
// 默认表单数据
const defaultForm = {
  noticeId: "",
  noticeTitle: "",
  noticeType: "",
  noticeContent: "",
  status: "0",
  createBy: "",
  createTime: "",
  updateBy: "",
  updateTime: "",
  isDeleted: 1,
};

const noticeTypeOptions = ref([
  { label: "通知", value: "1" },
  { label: "公告", value: "2" },
]);

// 表单模型，用于数据绑定和操作
const formModel = ref({ ...defaultForm });

// 表单规则
const rules = {
  noticeTitle: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
  noticeContent: [
    { required: true, message: "请输入公告标题", trigger: "blur" },
  ],
  noticeType: [{ required: true, message: "请选择公告类型", trigger: "blur" }],
};

// 打开抽屉函数------start
let titleDrawer = ref("编辑公告");
/**
 * 打开抽屉函数，根据传入的行数据和操作类型，决定是编辑、添加还是角色分配操作
 * @param {Object} row - 行数据
 * @param {String} operate - 操作类型
 */
const open = async (row, operate) => {
  console.log(row);
  visibleDrawer.value = true;
  if (row.noticeId) {
    console.log("编辑回显");
    formModel.value = row;
    titleDrawer.value = "编辑公告";
  }
  if (!row.noticeId) {
    console.log("添加功能");
    formModel.value = { ...defaultForm };
    titleDrawer.value = "添加公告";
  }
};
defineExpose({ open });
// 打开抽屉函数------end

// 添加或编辑操作-------start

let loadingAdd = ref(false); // 添加和编辑操作的加载状态

const formRef = ref(); // 表单引用，用于表单验证和提交

// 发送到父组件的成功事件
const emit = defineEmits(["success"]);
/**
 * 提交表单数据，根据是否有ID判断是进行编辑还是添加操作
 * @param {String} state - 表单状态（已发布或草稿）
 */
const onSubmit = async (state) => {
  await formRef.value.validate(); // 验证表单
  loadingAdd.value = true;
  console.log(formModel.value);
  try {
    if (formModel.value.noticeId) {
      console.log("编辑操作");
      // 将status转回1/0
      formModel.value.updateBy = userInfo.user.name;
      formModel.value.status = formModel.value.status == false ? "0" : "1";
      await noticeMgrUpdateService(formModel.value);
      ElMessage.success("编辑成功");
      visibleDrawer.value = false;
      emit("success", "edit");
    }

    if (!formModel.value.noticeId) {
      // 添加请求
      formModel.value.updateBy = userInfo.user.name;
      formModel.value.createBy = userInfo.user.name;
      formModel.value.status = formModel.value.noticeType == "2" ? "1" : "0";
      let res = await noticeMgrAddService(formModel.value);
      console.log(res);
      ElMessage.success("添加成功");
      visibleDrawer.value = false;
      emit("success", "add");
    }
  } catch (error) {
    formModel.value.status = formModel.value.status == 0 ? false : true;
    console.log(error);
  } finally {
    loadingAdd.value = false;
  }
};
// 添加或编辑操作-------end

// 切换用户状态-----start
// 加载状态的ref对象，用于状态切换的动画
let loadingStatus = ref(false);
</script>

<template>
  <!-- 抽屉组件，用于编辑和添加用户 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="titleDrawer"
    direction="rtl"
    size="60%"
    style="padding: 30px"
  >
    <!-- 表单组件，用于输入用户信息 -->
    <el-form
      :model="formModel"
      ref="formRef"
      :rules="rules"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
          v-model="formModel.noticeTitle"
          placeholder="请输入公告标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="公告内容" prop="noticeContent">
        <el-input
          v-model="formModel.noticeContent"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 25 }"
          show-word-limit
          style="width: 500px"
          placeholder="请输入公告内容"
        ></el-input>
      </el-form-item>

      <el-form-item label="公告类型" prop="noticeType">
        <el-select v-model="formModel.noticeType" placeholder="请选择公告类型">
          <el-option
            v-for="item in noticeTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 提交表单按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          :icon="Plus"
          :loading="loadingAdd"
          @click="onSubmit('已发布')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-input {
  max-width: 500px;
}
.el-select {
  max-width: 500px;
}
</style>
